package com.xjscrm.server.service.device.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaHeartBeatMsg;
import com.uzai.mobile.collect.api.dto.msg.MicaOfflineMsg;
import com.uzai.mobile.collect.api.dto.msg.MicaOnlineMsg;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.WwCorp;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.param.device.WwDeviceMobileCacheDto;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.server.common.util.ShortChainUtils;
import com.xjscrm.server.mapper.WwCorpMapper;
import com.xjscrm.server.mapper.WwDeviceMapper;
import com.xjscrm.server.service.common.CorpApplicationService;
import com.xjscrm.server.service.device.WwDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 企业微信机器人(WwDevice)表服务实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Service
@Slf4j
public class WwDeviceServiceImpl implements WwDeviceService {
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WwCorpMapper wwCorpMapper;
    @Autowired
    private CorpApplicationService corpApplicationService;

    /**
     * 处理机器人上线协议
     *
     * @param micaTransDto 上线实体类
     * @return 实例对象
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void online(MicaTransDto micaTransDto) {
        try {

            log.info("--监控系统日志--开始--");

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                return;
            }
            int now = DateUtil.getTime();
            MicaOnlineMsg micaOnlineMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaOnlineMsg.class);

            WwCorp wwCorp = null;
            if (micaOnlineMsg != null) {
                //企业id不为空，则先增加企业
                if (micaOnlineMsg.getCorpId() != null) {
                    wwCorp = wwCorpMapper.selectByCorpId(micaTransDto.getMerId(), String.valueOf(micaOnlineMsg.getCorpId()));
                    if (wwCorp == null) { //新增企业
                        wwCorp = new WwCorp();
                        wwCorp.setId(IdWorker.getId());
                        wwCorp.setMerId(micaTransDto.getMerId());
                        wwCorp.setCorpId(String.valueOf(micaOnlineMsg.getCorpId()));
                        wwCorp.setName(micaOnlineMsg.getCorpName());
                        wwCorp.setRemark(null);
                        wwCorp.setCreateTime(now);
                        wwCorp.setUpdateTime(now);
                        wwCorpMapper.insert(wwCorp);
                    }
                }

                //判断是否存在该企业微信
                WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
                if (wwDevice == null) { //不存在，则添加
                    wwDevice = new WwDevice();
                    wwDevice.setId(ShortChainUtils.creatShortId(IdWorker.getId())); //将雪花算法生成的ID转成11位
                    wwDevice.setMerId(micaTransDto.getMerId());
                    wwDevice.setDeviceId(micaTransDto.getDeviceId());
                    wwDevice.setDeviceName(micaOnlineMsg.getNickName());
                    wwDevice.setHeadImgUrl(micaOnlineMsg.getHeadImg());
                    wwDevice.setRemark(null);
                    wwDevice.setMobile(micaOnlineMsg.getMobile());
                    wwDevice.setMobiletype(micaOnlineMsg.getMobileType());
                    wwDevice.setLoginStatus(1); //上线
                    //wwDevice.setLastLoginIp();
                    wwDevice.setLastLoginTime(now);
                    wwDevice.setDeviceType(micaTransDto.getDeviceType());
                    wwDevice.setCorpId(String.valueOf(micaOnlineMsg.getCorpId()));
                    wwDevice.setOpenChat(0); //
                    wwDevice.setAcctId(micaOnlineMsg.getAcctId());
                    wwDevice.setCreateTime(now);
                    wwDevice.setUpdateTime(now);
                    //添加
                    wwDeviceMapper.insert(wwDevice);

                } else {
                    wwDevice.setMerId(micaTransDto.getMerId());
                    wwDevice.setDeviceName(micaOnlineMsg.getNickName());
                    wwDevice.setHeadImgUrl(micaOnlineMsg.getHeadImg());
                    wwDevice.setRemark(null);
                    wwDevice.setMobile(micaOnlineMsg.getMobile());
                    wwDevice.setMobiletype(micaOnlineMsg.getMobileType());
                    wwDevice.setLoginStatus(1); //上线
                    //wwDevice.setLastLoginIp();
                    wwDevice.setDeviceType(micaTransDto.getDeviceType());
                    wwDevice.setLastLoginTime(now);
                    wwDevice.setCorpId(String.valueOf(micaOnlineMsg.getCorpId()));
                    wwDevice.setAcctId(micaOnlineMsg.getAcctId());
                    wwDevice.setUpdateTime(now);
                    //修改
                    wwDeviceMapper.update(wwDevice);
                }

                //修改机器人信息缓存
                WwDeviceMobileCacheDto wwDeviceMobileCacheDto = new WwDeviceMobileCacheDto();
                wwDeviceMobileCacheDto.setImei(micaOnlineMsg.getImei());
                wwDeviceMobileCacheDto.setMerId(wwDevice.getMerId());
                wwDeviceMobileCacheDto.setDeviceId(wwDevice.getDeviceId());
                wwDeviceMobileCacheDto.setDeviceUniqueId(wwDevice.getId());
                wwDeviceMobileCacheDto.setDeviceType(wwDevice.getDeviceType());
                wwDeviceMobileCacheDto.setDeviceName(wwDevice.getDeviceName());
                wwDeviceMobileCacheDto.setDeviceRemark(wwDevice.getRemark());
                wwDeviceMobileCacheDto.setHeadImgUrl(wwDevice.getHeadImgUrl());
                wwDeviceMobileCacheDto.setLastHeartBeatTime(now);
                wwDeviceMobileCacheDto.setLastLoginTime(now);
                wwDeviceMobileCacheDto.setBatteryLevel(null);
                wwDeviceMobileCacheDto.setSdCardTotal(null);
                wwDeviceMobileCacheDto.setSdCardFree(null);
                wwDeviceMobileCacheDto.setNetType(null);
                wwDeviceMobileCacheDto.setWxVersion(null);
                wwDeviceMobileCacheDto.setClientVersion(null);
                String deviceCacheKey = String.format(RedisCacheKeyEnum.WW_DEVICE_MOBLE.getKey(), wwDevice.getId());
                redisTemplate.opsForValue().set(deviceCacheKey, JSONObject.toJSONString(wwDeviceMobileCacheDto));


                //处理企业应用
                corpApplicationService.handerCorpApplication(wwCorp, wwDevice);

            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("--监控系统日志--结束--");
        }

    }

    /**
     * 处理机器人心跳协议
     *
     * @param micaTransDto
     * @return 实例对象
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void heartBeat(MicaTransDto micaTransDto) {
        try {

            log.info("--监控系统日志--开始--");

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("未找到机器人wxid");
                return;
            }

            MicaHeartBeatMsg micaHeartBeatMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaHeartBeatMsg.class);
            if (micaHeartBeatMsg == null) {
                log.info("心跳信息为空");
                return;
            }

            //判断是否存在该企业微信
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                log.info("未找到此机器人");
                return;
            }

            int now = (int) (System.currentTimeMillis() / 1000L);

            //修改机器人信息缓存
            WwDeviceMobileCacheDto wwDeviceMobileCacheDto = new WwDeviceMobileCacheDto();
            wwDeviceMobileCacheDto.setImei(micaHeartBeatMsg.getImei());
            wwDeviceMobileCacheDto.setMerId(wwDevice.getMerId());
            wwDeviceMobileCacheDto.setDeviceId(wwDevice.getDeviceId());
            wwDeviceMobileCacheDto.setDeviceUniqueId(wwDevice.getId());
            wwDeviceMobileCacheDto.setDeviceType(wwDevice.getDeviceType());
            wwDeviceMobileCacheDto.setDeviceName(wwDevice.getDeviceName());
            wwDeviceMobileCacheDto.setDeviceRemark(wwDevice.getRemark());
            wwDeviceMobileCacheDto.setHeadImgUrl(wwDevice.getHeadImgUrl());
            wwDeviceMobileCacheDto.setLastLoginTime(wwDevice.getLastLoginTime());
            wwDeviceMobileCacheDto.setLastHeartBeatTime(now);
            wwDeviceMobileCacheDto.setBatteryLevel(null);
            wwDeviceMobileCacheDto.setSdCardTotal(null);
            wwDeviceMobileCacheDto.setSdCardFree(null);
            wwDeviceMobileCacheDto.setNetType(null);
            wwDeviceMobileCacheDto.setWxVersion(null);
            wwDeviceMobileCacheDto.setClientVersion(null);

            String deviceCacheKey = String.format(RedisCacheKeyEnum.WW_DEVICE_MOBLE.getKey(), wwDevice.getId());
            redisTemplate.opsForValue().set(deviceCacheKey, JSONObject.toJSONString(wwDeviceMobileCacheDto));

            String deviceLastHeatBeatTime = String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDevice.getDeviceId());
            redisTemplate.opsForValue().set(deviceLastHeatBeatTime, now, 5, TimeUnit.MINUTES);

            //处理企业应用
            WwCorp wwCorp = wwCorpMapper.selectByCorpId(micaTransDto.getMerId(), String.valueOf(wwDevice.getCorpId()));
            if (wwCorp != null) {
                //处理企业应用
                corpApplicationService.handerCorpApplication(wwCorp, wwDevice);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("--监控系统日志--结束--");
        }

    }

    /**
     * 处理机器人下线协议
     *
     * @param micaTransDto
     * @return 实例对象
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void offline(MicaTransDto micaTransDto) {

        try {
            log.info("--监控系统日志--开始--");
            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                return;
            }

            MicaOfflineMsg micaOfflineMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaOfflineMsg.class);

            //判断是否存在该企业微信
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }

            int now = DateUtil.getTime();

            wwDevice.setLoginStatus(0); //下线
            wwDevice.setUpdateTime(now);
            wwDeviceMapper.update(wwDevice);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("--监控系统日志--结束--");
        }

    }

}
